﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RoboContainer.Core;
using TimeMachine.Engine.Storing.Impl;
using TimeMachine.Engine.Vcs;

namespace TimeMachine.Engine.Agents
{
	public class DownloadDataAgent
	{
		private readonly IProjectSettings projectSettings;

		public DownloadDataAgent(IProjectSettings projectSettings)
		{
			this.projectSettings = projectSettings;
		}

		public string GetCsv()
		{
			var container = new Container(c => c.ForPlugin<IProjectSettings>().UseInstance(projectSettings));
			var metrics = container.Get<MetricsStorage>();
			var commitsProvider = container.Get<ICommitsInfoProvider>();
			IEnumerable<DetailedCommitInfo> commits = commitsProvider.Get();
			var stringWriter = new StringWriter();
			using (var writer = new CsvWriter(stringWriter))
			{
				writer.WriteField("revision");
				writer.WriteField("date");
				writer.WriteField("author");
				foreach (string metricName in metrics.KnownMetricIds())
					writer.WriteField(metricName);
				writer.WriteNextLine();
				foreach (DetailedCommitInfo commit in commits)
				{
					writer.WriteField(commit.Revision.ToString());
					writer.WriteField(commit.Date.ToShortDateString());
					writer.WriteField(commit.Author);
					foreach (string metricId in metrics.KnownMetricIds())
						writer.WriteField(metrics.GetValue(metricId, commit.Revision).Value.ToString(NumberFormatInfo.InvariantInfo));
					writer.WriteNextLine();
				}
				return stringWriter.GetStringBuilder().ToString();
			}
		}
	}
}